<?php

namespace app\admin\model;

use think\Model;

class AuthRule extends Model
{
    protected $autoWriteTimestamp = true;

    protected $auto = ['link'];

    /**
     * @param $value
     * @return string  自动完成插入链接
     */
    protected function setLinkAttr($value)
    {
        return url($value);
    }

    public static function getMenu($rules)
    {
        $menus = self::where('id', 'in', $rules)
            ->where(['ismenu'=>1,'status'=>1])
            ->field('id,pid,title name,icon,name as url')
            ->order('sorts')
            ->select();
        $menus = unlimitedtree($menus->toArray(),0,1,'pid','children',function (&$item){
            $item['url']=url($item['url']);
        });
        return $menus;
    }

    public function treeList()
    {
        $list = $this->order('sorts ASC,id ASC')->select();
        $list = unlimitedSort($list);
        return $list;
    }

    public function treeList2($pid = 0)
    {
        $list = $this->field('id,pid,name,title,icon as lay_icon,status,ismenu,sorts')->order('sorts ASC,id ASC')->select();
        return unlimitedSort($list,$pid);;
    }

    public function treeList3()
    {
        $list = $this->field('id,pid,title')->order('sorts ASC,id ASC')->select();
        $childNode='children';
        return unlimitedTree($list,0, 1,'pid',$childNode,function (&$item) use ($childNode){
            // 卸载掉空的数组元素
            if (!$item[$childNode] == null) {
                $item['spread'] = true;
            }
        });
    }

    public function getUserRule($rules)
    {
        $rules = explode(',', $rules);
        $list = $this->field('id,pid,title')->order('sorts ASC,id ASC')->select();
        $childNode='children';
        return unlimitedTree($list,0, 1,'pid',$childNode,function (&$item) use ($childNode,$rules){
            // 卸载掉空的数组元素
            if ($item[$childNode] == null) {
                if (in_array($item['id'], $rules)) {
                    $item['checked'] = true;
                }
            } else {
                $item['spread'] = true;
            }
        });
    }

    //获取面包屑
    public static function Crumbs($authrule,&$result='',$deep=0){
        if($authrule['pid']&&$deep<10){//$authrule存在，并且$authrule不为零,递归深度小于10
            $authrule=self::find($authrule['pid']);
            $result='<a href="'.url($authrule['name']).'">'.$authrule['title'].'</a>'.$result;
            self::Crumbs($authrule,$result,$deep++);
        }
        return $result;
    }
}